/**
 * Copyright (C) T-Systems International, 2013-2014
 *
 * The copyright of the computer program herein is the property of
 * T-Systems International. The program may be used and/or copied
 * only with the written permission of T-Systems International or in
 * accordance with the terms and conditions stipulated in the
 * agreement/contract under which the program has been supplied.
 *
 * $Author$
 * $Date$
 * $Rev$
 */
package com.tsystems.migdb;

import lombok.NonNull;
import lombok.extern.log4j.Log4j2;
import org.quartz.*;

import javax.annotation.concurrent.ThreadSafe;

@Log4j2
@ThreadSafe
public class JobManager {

    private final JobDetail jobDetail;
    private final TriggerKey triggerKey;
    private final Scheduler scheduler;

    public JobManager(@NonNull JobDetail jobDetail, @NonNull TriggerKey triggerKey, @NonNull Scheduler scheduler) {
        this.jobDetail = jobDetail;
        this.triggerKey = triggerKey;
        this.scheduler = scheduler;
    }

    public synchronized void register(long interval) throws SchedulerException {
        scheduler.scheduleJob(jobDetail, buildTrigger(interval));
    }

    public synchronized void resume() throws SchedulerException {
        scheduler.resumeJob(jobDetail.getKey());
    }

    public synchronized void reschedule(long interval) throws SchedulerException {
        scheduler.rescheduleJob(triggerKey, buildTrigger(interval));
    }

    public synchronized void delete() throws SchedulerException {
        scheduler.deleteJob(jobDetail.getKey());
    }

    public Trigger buildTrigger(long interval) {
        return TriggerBuilder.newTrigger()
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInMilliseconds(interval)
                        .repeatForever())
                .withIdentity(triggerKey)
                .startNow()
                .build();
    }

}